# -*- coding: utf-8 -*-
""" 
@author: ertao.xyz
@create: 2021-09-07 15:05
@description: 
"""
import json
from typing import List, Any
from datetime import timedelta

from fastapi import APIRouter, Depends, status, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.security.oauth2 import OAuth2PasswordRequestForm

from . import schema, model
from utils.response_code import ResultResponse, HttpStatus
from utils import logger
from utils.utils import verify_password
from auth.auth import create_access_token
from auth.auth_casbin import Authority
from utils import crud
from apps.user.common import getTreeData
from apps.user.model import Role

router = APIRouter()


@router.get("/getMenuList", summary="获取菜单")
async def getRoleMenu(request: Request):
    role = await Role.filter(value=request.state.user.role_id).first()
    query = await model.Menu.filter(id__in=role.menu)
    res = await getTreeData(query,
                            ['id', 'name', 'parent_id', 'path', 'component', 'permission',
                             'redirect', 'routerMeta'])
    return JSONResponse({'code': 200, 'message': 'ok', 'result': res})

    # role = request.state.user.role_id
    # obj = await model.RoleMenu.filter(role_id=role).first()
    # menus = json.loads(obj.menus)
    # return JSONResponse({'code': 200, 'message': 'ok', 'result': menus})


@router.get("/menu/list", summary="获取菜单列表", name='获取菜单列表')
async def menu_get_list():
    query = await model.Menu.all()
    res = await getTreeData(query,
                            ['id', 'name', 'title', 'parent_id', 'orderNo', 'icon', 'path', 'component', 'permission',
                             'status', 'isExt', 'show', 'redirect', 'created_at', 'type', 'routerMeta'])
    return ResultResponse(result=res)


@router.post('/menu/add',
             summary='添加菜单',
             name='添加菜单',
             response_model=ResultResponse[schema.MenuOut],
             dependencies=[Depends(Authority('menu,add'))])
async def add_menu(menu: schema.MenuCreate, request: Request):
    obj = await model.Menu.create(**menu.dict())
    return ResultResponse[schema.MenuOut](result=obj)


@router.put('/menu/update/{id}',
            summary='添加菜单',
            name='添加菜单',
            response_model=ResultResponse[schema.MenuOut],
            dependencies=[Depends(Authority('menu,update'))])
async def update_menu(id: int, data: schema.MenuCreate, request: Request):
    # has_obj = await model.Menu.filter(name=data.name).exclude(pk=id)
    # if has_obj:
    #     return ResultResponse[str](code=HttpStatus.HTTP_601_ROLE_EXIST, message='菜单已存在')
    obj = await model.Menu.get(pk=id)
    data = data.dict()
    if data['routerMeta'] == '':
        del data['routerMeta']
    obj = await model.Menu.update_from_dict(obj, data).save()
    return ResultResponse[schema.MenuOut](result=obj)


@router.delete('/menu/del',
               summary='删除菜单',
               name='删除菜单',
               response_model=ResultResponse[str],
               dependencies=[Depends(Authority('menu,del'))])
async def del_menu(request: Request, ids: schema.Ids):
    result = await crud.delete_obj_by_ids(model.Menu, ids.ids)
    if not result:
        return ResultResponse[str](code=HttpStatus.HTTP_600_ROLE_NOT_EXIST, message='菜单不存在')
    return ResultResponse[str](message='菜单已删除')


@router.get('/openapi/callback')
async def callback():
    return {"code":'ok'}